/**
 * Created by waterworld on 17-5-2.
 */
var http = require('http');
var https = require('https');
var qs = require('querystring');
var P=require('bluebird');
var  pb=require("protobufjs")
const WebSocket = require('ws');
var   protoRoot=null;
var Et = require('events').EventEmitter;
var util = require('util');
EventError=0
EventLogin =1
EventKeepAlive =2
EventEnter=3;

function  httpGet(url,cb)
{   var  html='';
    var req=http.get(url, function(res){
        res.on('data', function(data) {
            html+=data;
        }).on('end', function(){
            //cb(filePath);
            cb(0,html);
        }).on('error',function()
        {cb(0,null);});
    });
    req.on('error',function(err)
    {
        cb(0,null);
    });
}


function  httpPost(url,postData,cb)
{   var  html='';
    var  s=url.replace("http://","")
    var  pos= s.indexOf("/")
    var  host=""
    var  port="80"
    var  path="";
    if(pos>0)
    {
        host= s.substr(0,pos)
        path= s.substr(pos)
        pos=host.indexOf(":")
        if(pos>0)
        {
            port=host.substr(pos)
            host=host.substr(0,pos)
        }
    }
    var  options={
        host:host,
        port:port,
        path:path,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Content-Length': postData.length
        }}

    var post_req = http.request(options, function (response) {
        var responseText=[];
        var size = 0;
        response.on('data', function (data) {
            responseText.push(data);
            size+=data.length;
        });
        response.on('end', function () {
            // Buffer 是node.js 自带的库，直接使用
            responseText = Buffer.concat(responseText,size).toString('utf8');
            cb(0,responseText);
        });
        response.on('error', function () {
            // Buffer 是node.js 自带的库，直接使用
            responseText = Buffer.concat(responseText,size).toString('utf8');
            cb(0,responseText);
        });
    });

    // post the data
    post_req.write(postData);
    post_req.end();
}

var  httpPostAsync= P.promisify(httpPost);
var  httpGetAsync= P.promisify(httpGet);
var  loadProtoFile=P.promisify(pb.load)
exports.httpGetAsync= P.coroutine(function*(url)
{
    var ret=yield httpGetAsync(url);
    return ret;
});


exports.httpPostAsync= P.coroutine(function*(url,postData)
{
    var ret=yield httpPostAsync(url,postData);
    return ret;
});

exports.wsRequest= P.coroutine(function*(url,token,cmd,roomId){
    if(protoRoot==null)   protoRoot=yield loadProtoFile("./util/Message.proto")
    var    Ticker=function(){};
    util.inherits(Ticker,Et);
    var ticker = new Ticker();
    var loaded = new Promise(function(resolve, reject) {ticker.on("tick", resolve);});
    const ws = new WebSocket(url);
    var  gameMsg = protoRoot.lookup("pb.Msg");
    var  retData=null;
    ws.on('open', function open() {

        var m1=gameMsg.create({
            event:EventLogin,
            loginInfo:{
                id:token,
                enterParam:{
                    roomType:1,
                    roomId:roomId,
                },
                cmd:cmd
            },


        })

        var  buf=gameMsg.encode(m1).finish();
        ws.send(buf);
    });

    ws.on('message', function incoming(data) {
        console.log(data);
        var buffer = data;
        var msg = gameMsg.decode(new Uint8Array(buffer));
        console.logg("msg is "+JSON.stringify(msg))
        ticker.emit('tick',msg);
        retData=msg;
        ws.close()
    });

    ws.on('close', function close() {
        console.logg('disconnected');
        ticker.emit('tick',null);
    });
    ws.on("error",function error(e){
        console.logg('connect error',e.message);
        ticker.emit('tick',null);
    })

    yield loaded.then(function(data){
    });

    return retData;

})

String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if(args[key]!=undefined){
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
};

exports.post = function (host,port,path,data,callback) {

    var content = qs.stringify(data);
    var options = {
        hostname: host,
        port: port,
        path: path + '?' + content,
        method:'GET'
    };
    var req = http.request(options, function (res) {
        //console.log('STATUS: ' + res.statusCode);
        //console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            //console.log('BODY: ' + chunk);
            callback(chunk);
        });
    });
    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });
    req.end();
};

exports.get2 = function (url,data,callback,safe) {
    var content = qs.stringify(data);
    var url = url + '?' + content;
    var proto = http;
    console.logw('get2 ',url);
    if(safe){
        proto = https;
        console.logw('use https');
    }
    var req = proto.get(url, function (res) {
        //console.log('STATUS: ' + res.statusCode);
        //console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
            var json = JSON.parse(chunk);
            callback(null,json);
        });
        res.on('abort',function()
        {
            console.log('abort');
            callback(-1,'abort');
        });

    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
        callback(-1,e);
    });
    req.on('timeout',function()
    {
        console.log("timeout received");
        if (req.res) {
            req.res.emit("abort");
        }
        req.abort();
    });
    /*setTimeout(function()
    { req.emit("timeout");
    },5000);*/
    req.end();
};

exports.get = function (host,port,path,data,callback,safe) {
    var content = qs.stringify(data);
    var options = {
        hostname: host,
        path: path + '?' + content,
        method:'GET'
    };
    if(port){
        options.port = port;
    }
    var proto = http;
    if(safe){
        proto = https;
    }
    var req = proto.request(options, function (res) {
        //console.log('STATUS: ' + res.statusCode);
        //console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            //console.log('BODY: ' + chunk);
            var json = JSON.parse(chunk);
            callback(null,json);
        });
    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
        callback(-1,e);
    });

    req.end();
};

exports.send = function(res,errcode,errmsg,data){
    if(data == null){
        data = {};
    }
    data.errcode = errcode;
    data.errmsg = errmsg;
    var jsonstr = JSON.stringify(data);
    res.send(jsonstr);
};